// index.js
// 获取应用实例
const app = getApp();
Page({
  data: {
    dataUrlArr: [],
    imgUrl: "",
    deptOption: [],
    deptIndex: '',
    name: '', // 工单人详细地址 
    tel: '', // 电话
    money: '', // 装修数量
    reviewTel: '', // 复核信息
    explains: '', // 说明
    picture: '', // 照片最多三张多个逗号隔开
    total: '',
    fan: '', // 开扇数量
    door: '', // 开门数量
    tube: '', // 方管数量
    inversion: '', // 内倒数量
    transfer: '', // 转角数量
    window: '', // 纱窗数量
    packIndex: '', // 打包类目index
    packOption: [],
    brandIndex: '', // 品牌index
    brandOption: [],
    materialIndex: '', // 型号index
    materialOption: [],
    thicknessIndex: '', // 壁厚index
    thicknessOption: [],
    openIndex: '', // 开启
    openOption: [],
    ReimbursementData: [],
    array: [],
    // type: '--请选择--',
    dictLabel: '',
    dictCode: '',
    isUpload: false,
    fileLength: 0,
    loading: false,
    list: [
      { name: '打包类目', status: 0, listUrl: '/api/category/selPackList' },
      { name: '品牌', status: 1, listUrl: '/api/category/selBrandList' },
      { name: '型号', status: 2, listUrl: '/api/category/selMaterialList' },
      { name: '壁厚', status: 3, listUrl: '/api/category/selThicknessList' },
      { name: '开启', status: 4, listUrl: '/api/category/selOpenList' },
    ],
    fileList: [],
    checked: false,
    agreementShow: false,
    content: '',
    title: '',
    showGetPhone: false,
    showUser: false,
  },
  onLoad() {
    if (wx.getStorageSync('userPhone')) this.setData({ reviewTel: `【】${Number(wx.getStorageSync('userPhone'))}` || '' });
    wx.setStorageSync('financialCommit', false);
    const data = wx.getStorageSync('financialData');
    if (!!data) {
      this.setData({
        ...data,
      })
    }
    this.getDepartment();
    this.getDishuDepartment();
    this.getPrivery();
    wx.hideShareMenu();
    this.data.list.forEach(item => {
      this.getList(item.listUrl, item.status);
    })
  },
  onReady() {
  },
  onShow() {

  },
  //刷新
  onPullDownRefresh() {

  },

  getPrivery() {
    wx.request({
      url: `${app.globalData.baseUrl}/api/memo/sekByRuleId?id=2`,
      method: "GET",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        if (res.data.code == 0) {
          this.setData({ 
            content: res.data.data.content,
            title: res.data.data.title
          });
        }
      }
    })
  },

  // bindPickerChange: function (e) {
  //   var mchObj = this.data.ReimbursementData[e.detail.value];
  //   this.setData({
  //     index: e.detail.value,
  //     dictCode: mchObj.dictCode,
  //     dictLabel: mchObj.dictLabel,
  //     type: mchObj.dictValue
  //   })
  // },
  // 获取工单类型
  getDepartment() {
    wx.request({
      url: `${app.globalData.baseUrl}/api/finance/getDictData`,
      method: "GET",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      data: {
        dictType: 'sys_finance',
      },
      success: (res) => {
        if (res.data.code == 0) {
          this.setData({
            ReimbursementData: res.data.data,
          });
        }

      }
    })
  },

  //预览图片，放大预览
  preview(e) {
    let currentUrl = this.data.dataUrlArr;
    let index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: currentUrl[index], // 当前显示图片的http链接
      urls: this.data.dataUrlArr // 需要预览的图片http链接列表
    })
  },

  removeImage(e) {
    const arr = this.data.dataUrlArr;
    const index = e.currentTarget.dataset.index
    arr.splice(index, 1);
    this.setData({ dataUrlArr: arr })
  },
  // 详细地址
  handNameChange: function (e) {
    // 取出定义的变量名
    let targetData = e.currentTarget.dataset.modal;
    // 取出定义的变量名
    let currentValue = e.detail.value;
    // 将 input 值赋值给 定义的变量名，可以直接取到在 data 中定义的 变量 值，其效果跟 this[变量名] 是对等的，这是 js 基础
    this[targetData] = currentValue;
    //  console.log(this[targetData]);
    this.setData({
      name: this[targetData]
    })
  },
  telFocus: function (e) {
    if (!e.detail.value) this.setData({ tel: '【】' });
  },
  // 电话
  handTelChange(e) {
    // 取出定义的变量名
    let targetData = e.currentTarget.dataset.modal;
    // 取出定义的变量名
    let currentValue = e.detail.value;
    // 将 input 值赋值给 定义的变量名，可以直接取到在 data 中定义的 变量 值，其效果跟 this[变量名] 是对等的，这是 js 基础
    this[targetData] = currentValue;
    //  console.log(this[targetData]);
    this.setData({
      tel: this[targetData]
    })
  },
  // 装修数量
  handCompanyChange(e) {
    // 取出定义的变量名
    let targetData = e.currentTarget.dataset.modal;
    // 取出定义的变量名
    let currentValue = e.detail.value;
    // 将 input 值赋值给 定义的变量名，可以直接取到在 data 中定义的 变量 值，其效果跟 this[变量名] 是对等的，这是 js 基础
    this[targetData] = currentValue;
    this.setData({
      money: this[targetData]
    })
  },
  // 复核信息  reviewTel
  handLLicensePlateChange: function (e) {
    // 取出定义的变量名
    let targetData = e.currentTarget.dataset.modal;
    // 取出定义的变量名
    let currentValue = e.detail.value;
    // 将 input 值赋值给 定义的变量名，可以直接取到在 data 中定义的 变量 值，其效果跟 this[变量名] 是对等的，这是 js 基础
    this[targetData] = currentValue;
    //  console.log(this[targetData]);
    this.setData({
      reviewTel: this[targetData]
    })
  },
  reviewTelFocus(e) {
    if (!e.detail.value) this.setData({ reviewTel: '【】' });
  },
  // 说明
  handSubjectMatterChange(e) {
    this.setData({
      explains: e.detail.value
    })
  },
  //总额
  totalChange(e) {
    this.setData({
      total: e.detail.value
    });
  },
  hardwareOptionTap(e) {
    let Index = e.currentTarget.dataset.index;//获取点击的下拉列表的下标  hardwareName
    let that = this;
    that.setData({
      hardwareIndex: Index,
      hardwareShow: !this.data.hardwareShow
    });
    for (let h = 0; h <= that.data.hardwareData.length; h++) {
      if (Index == h) {
        that.setData({
          hardwareName: that.data.hardwareData[h].dictLabel
        })
      }
    }
  },

  getDishuDepartment() {
    wx.request({
      url: `${app.globalData.baseUrl}/api/finance/getDictData`,
      method: "GET",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      data: {
        dictType: 'sys_affiliated_unit',
      },
      success: (res) => {
        if (res.data.code == 0) {
          this.setData({
            deptOption: res.data.data,
          });
        }
      }
    })
  },

  bindPickerChange1: function (e) {
    this.setData({
      deptIndex: e.detail.value
    })
  },

  fanChange(e) {
    this.setData({ fan: e.detail.value });
  },

  doorChange(e) {
    this.setData({ door: e.detail.value });
  },

  tubeChange(e) {
    this.setData({ tube: e.detail.value });
  },

  inversionChange(e) {
    this.setData({ inversion: e.detail.value });
  },

  transferChange(e) {
    this.setData({ transfer: e.detail.value });
  },

  windowChange(e) {
    this.setData({ window: e.detail.value });
  },

  packChange: function (e) {
    this.setData({
      packIndex: e.detail.value,
    });
  },

  brandChange: function (e) {
    this.setData({
      brandIndex: e.detail.value,
    });
  },

  materialChange: function (e) {
    this.setData({
      materialIndex: e.detail.value,
    });
  },

  thicknessChange: function (e) {
    this.setData({
      thicknessIndex: e.detail.value,
    });
  },

  openChange: function (e) {
    this.setData({
      openIndex: e.detail.value,
    });
  },

  onChange(e) {
    this.setData({
      checked: e.detail
    })
  },

  closePhone(e) {
    this.setData({ showGetPhone: false });
    if (e.detail) this.setData({ showUser: true });
  },

  closeUser() {
    this.setData({ showUser: false });
  },

  // 提交
  appointmentApplication() {
    if (!wx.getStorageSync('userPhone')) {
      this.setData({ showGetPhone: true });
      return;
    }
    if (this.data.deptIndex == "") {
      wx.showToast({
        title: '请选择隶属归类',
        icon: 'error'
      })
    } else if (this.data.name == "") {
      wx.showToast({
        title: '请输入详细省市区+详细地址房号',
        icon: "none"
      })
    } else if (this.data.tel == "") {
      wx.showToast({
        title: '请输入微信可加的常用联系电话',
        icon: "none"
      })
    }else if (this.data.explains == "" || this.data.explains == undefined) {
      wx.showToast({
        title: '输入备注装修信息说明',
        icon: "none"

      })
    } else if (this.data.dataUrlArr == "") {
      wx.showToast({
        title: '请上传照片',
        icon: "none"
      })
    } else {
      if (this.data.dataUrlArr && this.data.dataUrlArr.length > 9) {
        wx.showToast({
          title: '最多上传9张图片',
          icon: "none"
        })
        return;
      }
      if (this.data.fileList && this.data.fileList.length > 9) {
        wx.showToast({
          title: '最多上传9个文件',
          icon: 'error'
        })
        return;
      }
      if (!this.data.total) {
        wx.showToast({
          title: '请输入预算装修金额',
          icon: "none"
        })
        return;
      } else if (this.data.reviewTel == "" || this.data.reviewTel == "【】") {
        wx.showToast({
          title: '请输入发起人名+常用电话',
          icon: "none"
        })
      }
      if(!this.data.checked) {
        wx.showToast({
          title: '请勾选协议',
          icon: 'error'
        });
        return
      }
      let photoStr = this.data.dataUrlArr.join(",");
      const fileStr = this.data.fileList.join(",");
      let _that = this;
      wx.showModal({
        content: '你确认提交工单吗',
        success: function (sm) {
          if (sm.confirm) {
            _that.setData({ loading: true });
            wx.showLoading();
            wx.request({
              url: `${app.globalData.baseUrl}/api/finance/saveFinance`,
              method: "POST",
              data: {
                name: _that.data.name,
                tel: _that.data.tel,
                // type: _that.data.type,
                money: _that.data.money,
                reviewTel: _that.data.reviewTel,
                explains: _that.data.explains,
                picture: photoStr, // 照片最多三张多个逗号隔开
                attachment: fileStr, //附件
                affiliated: _that.data.deptOption[_that.data.deptIndex]?.dictValue,
                total: parseFloat(_that.data.total).toFixed(2),
                fan: _that.data.fan ? Number(_that.data.fan) : '', // 开扇数量
                door: _that.data.fan ? Number(_that.data.door) : '', // 开门数量
                tube: _that.data.fan ? Number(_that.data.tube) : '', // 方管数量
                inversion: _that.data.fan ? Number(_that.data.inversion) : '', // 内倒数量
                transfer: _that.data.fan ? Number(_that.data.transfer) : '', // 转角数量
                window: _that.data.fan ? Number(_that.data.window) : '', // 纱窗数量
                pack: _that.data.packIndex != '' ? _that.data.packOption[_that.data.packIndex].dictCode : '', // 打包类目
                brandId: _that.data.brandIndex != '' ? _that.data.brandOption[_that.data.brandIndex].dictCode : '', // 品牌
                materialId: _that.data.materialIndex != '' ? _that.data.materialOption[_that.data.materialIndex].dictCode : '', // 型号
                thicknessId: _that.data.thicknessIndex != '' ? _that.data.thicknessOption[_that.data.thicknessIndex].dictCode : '', // 壁厚
                openId: _that.data.openIndex != '' ? _that.data.openOption[_that.data.openIndex].dictCode : '',
              },
              header: {
                "Content-Type": "application/json",
                'token': wx.getStorageSync('token'),
              },
              success: (res) => {
                wx.hideLoading();
                if (res.data.code == 0) {
                  wx.showToast({
                    title: res.data.msg || '报错啦！',
                    duration: 2000
                  })
                  wx.setStorageSync('financialCommit', true);
                  _that.setData({
                    name: '',
                    tel: '',
                    // type: '--请选择--',
                    money: '',
                    reviewTel: '',
                    explains: '',
                    picture: '',
                    deptIndex: '',
                    dataUrlArr: [],
                    index: '',
                    dictLabel: '',
                    dictCode: '',
                    total: '',
                    packIndex: '', // 打包类目index
                    brandIndex: '', // 品牌index
                    materialIndex: '', // 型号index
                    thicknessIndex: '', // 壁厚index
                    openIndex: '', // 开启
                    pack: '', // 打包类目
                    brandId: '', // 品牌
                    materialId: '', // 型号
                    thicknessId: '', // 壁厚
                    openId: '',
                    fan: '',
                    door: '',
                    tube: '',
                    inversion: '',
                    transfer: '',
                    window: ''
                  });
                  // TOO  添加财务工单页面
                  wx.switchTab({
                    url: '/pages/myReimbursement/index',
                    success() {
                      var page = getCurrentPages().pop();
                      if (page == undefined || page == null) return;
                      page.onLoad();
                    }
                  })
                } else if (res.data.code == 500) {
                  wx.showToast({
                    title: res.data.msg || '报错啦！',
                    icon: 'error',//当icon：'none'时，没有图标 只有文字
                    duration: 2000
                  })
                  _that.setData({
                    isDisabled: false
                  })
                } else {
                  wx.showToast({
                    title: '系统错误，请重新登录',
                  })
                }
              },
              fail: () => {
                wx.hideLoading();
                wx.showToast({
                  title: '系统错误',
                });
                _that.setData({ loading: false });
              }

            })
          }
        }
      })
    }
  },
  uploadOpen: function (e) {
    this.setData({
      isUpload: true,
      fileLength: this.data.dataUrlArr.length,
      explains: this.data.explains ? this.data.explains : ' ',
    });
  },
  uploadClose: function () {
    this.setData({
      isUpload: false,
      explains: this.data.explains?.trim() ? this.data.explains : '',
    });
  },
  receivingData: async function (val) {
    this.setData({
      dataUrlArr: [...this.data.dataUrlArr, val.detail]
    });
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    const _that = this;
    wx.setStorageSync('financialData', {
      name: _that.data.name,
      tel: _that.data.tel,
      type: _that.data.type,
      money: _that.data.money,
      reviewTel: _that.data.reviewTel,
      explains: _that.data.explains,
      dataUrlArr: _that.data.dataUrlArr, // 照片最多三张多个逗号隔开
      index: _that.data.index,
      dictCode: _that.data.dictCode,
      dictLabel: _that.data.dictLabel,
      deptIndex: _that.data.deptIndex,
      total: _that.data.total,
      packIndex: _that.data.packIndex, // 打包类目index
      brandIndex: _that.data.brandIndex, // 品牌index
      materialIndex: _that.data.materialIndex, // 型号index
      thicknessIndex: _that.data.thicknessIndex, // 壁厚index
      openIndex: _that.data.openIndex, // 开启
      pack: _that.data.pack, // 打包类目
      brandId: _that.data.brandId, // 品牌
      materialId: _that.data.materialId, // 型号
      thicknessId: _that.data.thicknessId, // 壁厚
      openId: _that.data.openId,
      fan: _that.data.fan,
      door: _that.data.door,
      tube: _that.data.tube,
      inversion: _that.data.inversion,
      transfer: _that.data.transfer,
      window: _that.data.window
    });
  },

  getList(url, status) {
    wx.request({
      url: `${app.globalData.baseUrl}${url}`,
      method: "GET",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        if (res.data.code == 0) {
          const arr = res.data.rows;
          arr.forEach(item => {
            if (status == 2) {
              item.dictCode = item.materialId;
              item.dictLabel = item.materialName;
            } else {
              item.dictCode = item.id;
              item.dictLabel = item.name;
            }
          });
          if (status == 0) this.setData({ packOption: arr });
          if (status == 1) this.setData({ brandOption: arr });
          if (status == 2) this.setData({ materialOption: arr });
          if (status == 3) this.setData({ thicknessOption: arr });
          if (status == 4) this.setData({ openOption: arr });
        } else {
          wx.showToast({
            title: res.data.msg || '出错啦！',
            icon: 'error',
            duration: 2000
          })
        }
      }
    })
  },

  //隐私上传
  fujianafterRead(event) {
    const that = this;
    wx.chooseMessageFile({
      count: 9,
      type: 'file',
      extension: ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf'],
      success(res) {
        const tempFilePaths = res.tempFiles[0].path
        wx.uploadFile({
          url: `${app.globalData.baseUrl}/common/upload`, // 仅为示例，非真实的接口地址
          filePath: tempFilePaths,
          name: 'file',
          formData: {
            user: 'test'
          },
          success(res) {
            res.data = JSON.parse(res.data)
            const item = res.data.url;
            that.setData({
              fileList: [...that.data.fileList, item]
            })
          },
        });
      }
    })
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  },

  removeWord(e) {
    const arr = this.data.fileList;
    const index = e.currentTarget.dataset.index
    arr.splice(index, 1);
    this.setData({ fileList: arr })
  },

  download(e) {
    const that = this;
    wx.getSystemInfo({
      success: function(result) {
        if (result.platform === 'ios' || result.platform === 'android') {
          that.saveMobile(e.currentTarget.dataset.url);
        } else if (result.platform === 'windows' || result.platform === 'mac') {
          that.savePc(e.currentTarget.dataset.url);
        }
      }
    });
  },

  savePc(url) {
    wx.request({
      url: url,
      responseType: 'arraybuffer', // 设置响应类型为arraybuffer以接收二进制数据
      success: (res) => {
        // 获取文件名
        const fileName = url.split('/').pop();
     
        // 写入文件
        wx.getFileSystemManager().writeFile({
          filePath: wx.env.USER_DATA_PATH + '/' + fileName, // 指定要写入的文件路径
          data: res.data, // 文件内容
          encoding: 'binary', // 指定文件编码
          success: (writeRes) => {
            console.log('文件保存成功', writeRes);
            // 这里可以调用wx.saveFileToDisk将文件保存到用户电脑
            wx.saveFileToDisk({
              filePath: wx.env.USER_DATA_PATH + '/' + fileName,
              success: (saveRes) => {
                console.log('文件保存到电脑成功', saveRes);
              },
              fail: (error) => {
                console.error('文件保存到电脑失败', error);
              }
            });
          },
          fail: (error) => {
            console.error('文件保存失败', error);
          }
        });
      },
      fail: (error) => {
        console.error('文件下载失败', error);
      }
    });
  },

  agreement() {
    this.setData({ agreementShow: true });
  },

  closeModal() {
    this.setData({ agreementShow: false });
  },

  setManage() {
    this.setData({ checked: true, agreementShow: false });
  },

  saveMobile(url) {
    console.log(url, 'mobile')
    wx.downloadFile({
      url,
      success(res) {
        if (res.statusCode === 200) {
          console.log(res.tempFilePath)
          wx.openDocument({
            filePath: res.tempFilePath,
            showMenu: true
          });
        }
      }
    })
  },
});